function parseAttributes(attributeString) {
    for (var attributes = {}, attributeArray = attributeString.split(","), index = 0; index < attributeArray.length; index++) attributes[attributeArray[index]] = !0;
    return attributes;
}

function removeXmlAndDoctypeTags(htmlContent) {
    return htmlContent.replace(/<\?xml.*\?>\n/, "").replace(/<.*!doctype.*\>\n/, "").replace(/<.*!DOCTYPE.*\>\n/, "");
}

function cleanHtmlContent(htmlContent) {
    return htmlContent.replace(/\r?\n+/g, "").replace(/<!--.*?-->/gi, "").replace(/\/\*.*?\*\//gi, "").replace(/[ ]+</gi, "<");
}

function processEmojis(textContent) {
    var nodes = [];
    if (0 == emojiKeys.length || !emojiMap) return (currentNode = {
        node: "text"
    }).text = textContent, nodes = [ currentNode ];
    textContent = textContent.replace(/\[([^\[\]]+)\]/g, ":$1:");
    for (var attributeRegex = new RegExp("[:]"), nodeArray = textContent.split(attributeRegex), index = 0; index < nodeArray.length; index++) {
        var currentNodeContent = nodeArray[index], currentNode = {};
        emojiMap[currentNodeContent] ? (currentNode.node = "element", currentNode.tag = "emoji", currentNode.text = emojiMap[currentNodeContent], currentNode.baseSrc = emojiBaseUrl) : (currentNode.node = "text", 
        currentNode.text = currentNodeContent), nodes.push(currentNode);
    }
    return nodes;
}

function getValueFromObject() {
    var result, argumentCount = arguments.length;
    if (2 !== argumentCount && 3 !== argumentCount) throw "必须为两个或者三个参数";
    if (3 === argumentCount) {
        var argumentArray = Array.prototype.slice.call(arguments), objectKeys = argumentArray[0], targetObject = argumentArray[1], defaultValue = argumentArray[2];
        result = defaultValue;
    } else {
        var argumentArray = Array.prototype.slice.call(arguments);
        targetObject = argumentArray[0], defaultValue = argumentArray[1];
    }
    if (!Array.isArray(objectKeys)) throw "参数有误，取值的keys必须为数组";
    try {
        objectKeys.forEach(function(key) {
            targetObject = targetObject[key];
        });
    } catch (error) {
        return result;
    }
    return targetObject;
}

var protocol = "https", emojiKeys = "", emojiBaseUrl = "", emojiMap = {}, stringDiscodeModule = require("./wxDiscode.js"), htmlParserModule = require("./htmlparser.js"), blockTags = (parseAttributes("area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr"), 
parseAttributes("br,a,code,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video")), inlineTags = parseAttributes("abbr,acronym,applet,b,basefont,bdo,big,button,cite,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var"), selfClosingTags = parseAttributes("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");

parseAttributes("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected"), 
parseAttributes("wxxxcode-style,script,style,view,scroll-view,block");

module.exports = {
    html2json: function(htmlContent, rootNodeName) {
        htmlContent = cleanHtmlContent(htmlContent = removeXmlAndDoctypeTags(htmlContent)), htmlContent = stringDiscodeModule.strDiscode(htmlContent);
        var nodesStack = [], rootNode = {
            node: rootNodeName,
            nodes: [],
            images: [],
            imageUrls: []
        }, nodeIndex = 0;
        return htmlParserModule(htmlContent, {
            start: function(tagName, attributes, isEmptyTag) {
                var currentNode, newNode = {
                    node: "element",
                    tag: tagName
                };
                if (0 === nodesStack.length ? (newNode.index = nodeIndex.toString(), nodeIndex += 1) : (void 0 === (currentNode = nodesStack[0]).nodes && (currentNode.nodes = []), 
                newNode.index = currentNode.index + "." + currentNode.nodes.length), blockTags[tagName] ? newNode.tagType = "block" : inlineTags[tagName] ? newNode.tagType = "inline" : selfClosingTags[tagName] && (newNode.tagType = "closeSelf"), 
                0 !== attributes.length && (newNode.attr = attributes.reduce(function(attributeObject, attribute) {
                    var attributeName = attribute.name, attributeValue = attribute.value;
                    return "class" == attributeName && (newNode.classStr = attributeValue), "style" == attributeName && (newNode.styleStr = attributeValue), attributeValue.match(/ /) && (attributeValue = attributeValue.split(" ")), 
                    attributeObject[attributeName] ? Array.isArray(attributeObject[attributeName]) ? attributeObject[attributeName].push(attributeValue) : attributeObject[attributeName] = [ attributeObject[attributeName], attributeValue ] : attributeObject[attributeName] = attributeValue, attributeObject;
                }, {})), "img" === newNode.tag) {
                    newNode.imgIndex = rootNode.images.length;
                    var httpProtocol = wx.getStorageSync("http");
                    if ("data:image/" != (imageSrc = newNode.attr.src).substr(0, 11).toLowerCase()) if ("http://" == imageSrc.substr(0, 7).toLowerCase() || "https://" == imageSrc.substr(0, 8).toLowerCase()) var fullImageSrc = newNode.attr.src; else fullImageSrc = httpProtocol + newNode.attr.src; else fullImageSrc = newNode.attr.src;
                    "" == fullImageSrc[0] && fullImageSrc.splice(0, 1), fullImageSrc = stringDiscodeModule.urlToHttpUrl(fullImageSrc, protocol), newNode.attr.src = fullImageSrc, newNode.from = rootNodeName, 
                    rootNode.images.push(newNode), rootNode.imageUrls.push(fullImageSrc);
                }
                if ("iframe" === newNode.tag && (newNode.vid = getValueFromObject([ 1 ], newNode.attr.src.match(/https:\/\/v\.qq\.com.*vid=(\w*)/))), 
                "font" === newNode.tag) {
                    var fontSizeOptions = [ "x-small", "small", "medium", "large", "x-large", "xx-large", "-webkit-xxx-large" ], attributeMapping = {
                        color: "color",
                        face: "font-family",
                        size: "font-size"
                    };
                    for (var attributeName in newNode.attr.style || (newNode.attr.style = []), newNode.styleStr || (newNode.styleStr = ""), 
                    attributeMapping) if (newNode.attr[attributeName]) {
                        var attributeValue = "size" === attributeName ? fontSizeOptions[newNode.attr[attributeName] - 1] : newNode.attr[attributeName];
                        newNode.attr.style.push(attributeMapping[attributeName]), newNode.attr.style.push(attributeValue), newNode.styleStr += attributeMapping[attributeName] + ": " + attributeValue + ";";
                    }
                }
                if ("source" === newNode.tag) {
                    var imageSrc, sourceProtocol = wx.getStorageSync("http");
                    "http://" == (imageSrc = newNode.attr.src).substr(0, 7).toLowerCase() || "https://" == imageSrc.substr(0, 8).toLowerCase() ? rootNode.source = newNode.attr.src : rootNode.source = sourceProtocol + newNode.attr.src;
                }
                isEmptyTag ? (void 0 === (currentNode = nodesStack[0] || rootNode).nodes && (currentNode.nodes = []), currentNode.nodes.push(newNode)) : nodesStack.unshift(newNode);
            },
            end: function(tagName) {
                var currentNode = nodesStack.shift();
                if (currentNode.tag !== tagName && console.error("invalid state: mismatch end tag"), "video" === currentNode.tag && rootNode.source && (currentNode.attr.src = rootNode.source, 
                delete rootNode.source), 0 === nodesStack.length) rootNode.nodes.push(currentNode); else {
                    var parentNode = nodesStack[0];
                    void 0 === parentNode.nodes && (parentNode.nodes = []), parentNode.nodes.push(currentNode);
                }
            },
            chars: function(textContent) {
                var textNode = {
                    node: "text",
                    text: textContent,
                    textArray: processEmojis(textContent)
                };
                if (0 === nodesStack.length) textNode.index = nodeIndex.toString(), nodeIndex += 1, rootNode.nodes.push(textNode); else {
                    var parentNode = nodesStack[0];
                    void 0 === parentNode.nodes && (parentNode.nodes = []), textNode.index = parentNode.index + "." + parentNode.nodes.length, 
                    parentNode.nodes.push(textNode);
                }
            },
            comment: function(commentContent) {}
        }), rootNode;
    },
    emojisInit: function(emojiKeyPrefix, emojiBaseUrlParam, emojiMapParam) {
        var emojiKeyPrefixParam = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : "", emojiBaseUrlParam = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : "/wxParse/emojis/", emojiMapParam = arguments[2];
        emojiKeys = emojiKeyPrefixParam, emojiBaseUrl = emojiBaseUrlParam, emojiMap = emojiMapParam;
    }
};